#pragma once
#include <iostream>
#include <cstring>
#include <string>
#include <functional>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>

#include "Log.hpp"
#include "InetAddr.hpp"
#include "Command.hpp"

const static int gport = 8888;
const static int gsockfd = -1;
const static int gblcklog = 8;//这个数不要太大
enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR
};

using command_serve_t = std::function<void(int sockfd, InetAddr addr)>;

class Sever
{
public:
    Sever(command_serve_t serve, uint16_t port = gport, int sockfd = gsockfd)
    :_serve(serve)
    ,_port(port)
    ,_listenSockfd(sockfd)
    ,_ifRunning(false)
    {}
    void Init()
    {
        //1. 创建sockfd
        _listenSockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_listenSockfd < 0)
        {
            LOG(FATAL, "socket creat error\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket creat success,sockfd: %d\n", _listenSockfd);
       
        //2. 本地ip和端口号和sockfd进行绑定
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        if(bind(_listenSockfd, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind success\n");

        //3.将sockfd设置为listen状态，未来远端的客户端可以发起连接，服务端能够做到不断获取连接
        if(listen(_listenSockfd, gblcklog) < 0)
        {
            LOG(FATAL, "set listen error\n");
            exit(LISTEN_ERROR);
        }
        LOG(INFO, "listen success\n");
    }
    struct ThreadData
    {
        ThreadData(int sockfd, InetAddr addr, Sever* psever)
        :_sockfd(sockfd)
        ,_addr(addr)
        ,_psever(psever)
        {}
        int _sockfd;
        InetAddr _addr;
        Sever* _psever;
    };
    void Loop()
    {
        _ifRunning = true;
        while(_ifRunning)
        {
            //4.接受连接
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            //当_sockfd没有获取到一个连接时，accept会阻塞，等待_sockfd获取到链接会返回一个sockfd
            int sockfd = accept( _listenSockfd, (struct sockaddr*)&client, &len);
            if(sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                continue;
            }
            InetAddr client_addr(client);
            LOG(INFO, "get a new link, client info: %s\n", client_addr.AddrStr().c_str());

            //V2-多线程版
            pthread_t tid;
            //td必须是动态开辟出来的
            ThreadData* td = new ThreadData(sockfd, client_addr, this);
            pthread_create(&tid, nullptr, Execute, td);
        }
        _ifRunning = false;
    }
    static void* Execute(void* args)
    {
        pthread_detach(pthread_self());//将自己和主线程分离
        ThreadData* td = static_cast<ThreadData*>(args);
        td->_psever->_serve(td->_sockfd, td->_addr);
        close(td->_sockfd);
        delete td;
        return nullptr;
    }
    ~Sever()
    {}
private:
    uint16_t _port;
    int _listenSockfd;
    bool _ifRunning;
    command_serve_t _serve;
};
